package com.ms.service.module.account;

import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

import com.ms.game.common.message.ServerReadyAction;
import com.ms.game.login.AccountKickPlayerInfo;
import com.xpec.c4.service.module.gateway.CGatewayLoadingInfo;

public class AccountCollectionInfo 
{
	private static AccountCollectionInfo singleton = new AccountCollectionInfo();
	static public AccountCollectionInfo getInstance() { return singleton; }
	
	/////////////////////////////////////////////////////////////////////////

	private ArrayList<CGatewayLoadingInfo> gateways;
	private ConcurrentHashMap<Object, AccountKickPlayerInfo > recvKickPLayerResult = new ConcurrentHashMap<Object, AccountKickPlayerInfo >();

	
	
	
	
	public AccountCollectionInfo()
	{
		gateways = new ArrayList<CGatewayLoadingInfo>();
	}
	
	public void setGatewayLoadingInfo(CGatewayLoadingInfo info)
	{
		for(CGatewayLoadingInfo data : gateways)
		{
			if( data.name.equals(info.name) )
			{
				data.gatewayIP = info.gatewayIP;
				data.gatewayPort = info.gatewayPort;
				data.playerConnectCount = info.playerConnectCount;
				data.robotConnectCount = info.robotConnectCount;
				return;
			}
		}
		
		gateways.add(info);

		// 收到 gateway 狀態，表示可以開始接受登入了
		if (gateways.size() == 1) {
			// 廣播給所有的 module
			ServerReadyAction.broadcastServerReadyNotify();
		}
	}
	
	public void removeGatewayLoadingInfo(String name)
	{
		for(CGatewayLoadingInfo data : gateways)
		{
			if( data.name.equals(name) )
			{
				gateways.remove(data); 

				System.out.println("CGatewayLoadingInfo - " + name + " remove");
				return;
			}
		}
	}

	/**
	 * 新增一個踢人的task
	 * @param key
	 * @return
	 */
	public Object addKickPlayerRequestInfo(String key){
		if(this.recvKickPLayerResult.contains(key))
			 return null;
		
		//lock用的所
		Object result = new Object();
		AccountKickPlayerInfo info = new AccountKickPlayerInfo();
		info.setLockObject(result);
		recvKickPLayerResult.put(key, info);
		return result;
	}
	/**
	 * 後臺剔除玩家的call back
	 * @param key
	 * @return
	 */
	public AccountKickPlayerInfo getKickPlayerResult(Object key , boolean isDelete){
		if(this.recvKickPLayerResult.containsKey(key)){
			AccountKickPlayerInfo result = this.recvKickPLayerResult.get(key);
			if(isDelete){
				this.recvKickPLayerResult.remove(key);
			}
			return result;
		}
		return null;
	}
	
	public int getAvailbleGatewaySize(){
		return this.gateways.size();
	}

	/**
	 * 取得所有的玩家數量
	 * @return
	 */
	public int getTotalPlayerCount() {
		int cnt = 0;

		if (gateways != null) {
			for (CGatewayLoadingInfo data : gateways) {
				cnt += data.playerConnectCount;
			}
		}

		return cnt;
	}
	
	/**
	 * 取得所有的機器人數量
	 * @return
	 */
	public int getTotalRobotCount() {
		int cnt = 0;

		if (gateways != null) {
			for (CGatewayLoadingInfo data : gateways) {
				cnt += data.robotConnectCount;
			}
		}

		return cnt;
	}
}
